package seqlist.oj;

public class NewCoder_PalindromeList {
    // 回文链表 = 中间节点 + 链表转置(原地转置，确实是将原链表做了倒置)
    public boolean chkPalindrome(ListNode A) {
        // 找到中间节点
        ListNode middle = middleNode(A);
        // 倒置后半部分链表
        ListNode B = reverse(middle);
        while (A != null && B != null) {
            if (A.val != B.val) {
                return false;
            }
            A = A.next;
            B = B.next;
        }
        return true;
    }
    // 找中间节点，快慢指针
    public ListNode middleNode(ListNode head) {
        ListNode low = head,fast = head;
        while (fast != null && fast.next != null) {
            low = low.next;
            fast = fast.next.next;
        }
        return low;
    }
    // 链表倒置(递归)
    public ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode tmpNext = head.next;
        // 将第二个节点之后的所有节点的倒置工作交给reverse
        ListNode newHead = reverse(head.next);
        // 处理头节点的情况
        tmpNext.next = head;
        head.next = null;
        return newHead;
    }
}
